
using System;
using System.Collections.Generic;
using System.IO;

namespace Designer
{
	public class FileResourceMgr:SingletonManager<FileResourceMgr>
	{
		public List<FileResource> Resources = new List<FileResource>();
		public void Clean()
		{
			foreach(FileResource fr in Resources)
			{
				fr.Unload();
			}
			Resources.Clear();
		}
	}
	
	public class FileResource
	{
		string origFile;
		string tempFile;
		
		public FileResource()
		{
			tempFile = "";
			origFile = "";
			FileResourceMgr.Instance.Resources.Add(this);
		}
		public string TempFile
		{
			get
			{
				return tempFile;
			}
			set
			{
				tempFile = value;
				origFile = tempFile.Substring(0,tempFile.LastIndexOf("."));
			}
		}
		public string OrigFile
		{
			get
			{
				return origFile;
			}
		}
		public void Load(string path)
		{
			Unload();
			string basename = new FileInfo(path).Name;
			int i = 0;
			string file;
			do
			{
				file = ResourceMgr.Instance.tempDir+basename+"."+(++i).ToString();
			}
			while(File.Exists(file));
			File.Copy(path,file);
			
			origFile = basename;
			tempFile = basename+"."+i.ToString();
		}
		public void Unload()
		{
			if(tempFile != "")
			{
				Console.WriteLine("Deleting "+ResourceMgr.Instance.tempDir+tempFile);
				File.Delete(ResourceMgr.Instance.tempDir+tempFile);
			}
		}
		public void Destroy()
		{
			FileResourceMgr.Instance.Resources.Remove(this);
			Unload();
		}
	}
}
